<template>
	<div class="user-role-user-container">
		<Button type="error" icon="md-add" @click="onAdd">新增用户</Button>
		<div class="ivu-inline-block ivu-fr">
			<Dropdown @on-click="onChangeTableSize" trigger="click">
				<Tooltip class="ivu-ml" content="密度" placement="top">
					<i-link>
						<Icon type="md-list" />
					</i-link>
				</Tooltip>
				<template #list>
					<DropdownMenu>
						<DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
						<DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
						<DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
					</DropdownMenu>
				</template>
			</Dropdown>
			<Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
				<i-link @click="onFullscreen">
					<Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'" />
				</i-link>
			</Tooltip>
			<Tooltip class="ivu-ml" content="刷新" placement="top">
				<i-link @click="onRefresh">
					<Icon custom="i-icon i-icon-refresh" />
				</i-link>
			</Tooltip>
			<Dropdown trigger="click">
				<Tooltip class="ivu-ml" content="列设置" placement="top">
					<i-link>
						<Icon type="md-options" />
					</i-link>
				</Tooltip>
				<template #list>
					<DropdownMenu>
						<div class="ivu-p-8">列展示</div>
						<Divider size="small" class="ivu-mt-8 ivu-mb-8" />
						<li class="ivu-dropdown-item" v-for="item in dropdownColumns" :key="item.title"
							@click="item.show = !item.show">
							<Checkbox v-model="item.show"></Checkbox>
							<span>{{ item.title }}</span>
						</li>
					</DropdownMenu>
				</template>
			</Dropdown>
		</div>
		<Table ref="table" :columns="tableColumns" :data="list" :loading="loading" :size="tableSize" class="ivu-mt">
			<template #name="{ row }">
				<Avatar shape="square" :src="row.headimgUrl" v-if="row.headimgUrl" />
				<Avatar shape="square" icon="ios-person" v-else />
				<span style="margin-left: 5px;">{{ row.name }}</span>
			</template>
			<template #status="{ row }">
				<Badge status="success" v-if="row.status === 0">
					<template #text>
						<span style="font-size: 12px;">在职</span>
					</template>
				</Badge>
				<Badge status="error" v-else>
					<template #text>
						<span style="font-size: 12px;">离职</span>
					</template>
				</Badge>
			</template>
			<template #action="{ row }">
				<div @click.stop.prevent>
					<Poptip confirm title="您确定删除该员工了吗？" transfer @on-ok="onDeleteUser(row)">
						<a style="color: #ed4014;">删除</a>
					</Poptip>
					<Divider type="vertical" />
					<Poptip confirm title="您确定重置该员工密码吗？" transfer @on-ok="onResetPassword(row)">
						<a style="color: #f90;">重置密码</a>
					</Poptip>
				</div>
			</template>
		</Table>
		<div class="ivu-mt ivu-text-center">
			<Page :total="total" v-model="pageNum" show-total show-sizer show-elevator :page-size="pageSize"
				@on-change="onChangePage" @on-page-size-change="onChangePageSize" />
		</div>
		<Modal title="新增用户" v-model="addVisible" @on-cancel="onCancelAdd" class-name="add-user-modal"
			:mask-closable="false">
			<Form ref="addInfo" :model="addInfo" :rules="addRules">
				<Row :gutter="16">
					<Col span="24">
					<FormItem label="用户名" prop="username">
						<Input v-model="addInfo.username" placeholder="请输入用户名"></Input>
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="手机号" prop="phoneNo">
						<Input v-model="addInfo.phoneNo" placeholder="请输入手机号" :maxlength="11"></Input>
					</FormItem>
					</Col>
				</Row>
			</Form>
			<template #footer>
				<Button type="text" @click="onCancelAdd">取消</Button>
				<Button type="primary" @click="onConfirmAdd" :loading="loading">确定</Button>
			</template>
		</Modal>
		<Modal title="更新用户" v-model="updateVisible" @on-cancel="onCancelUpdate" class-name="add-user-modal"
			:mask-closable="false">
			<Form ref="updateInfo" :model="updateInfo" :rules="updateRules">
				<Row :gutter="16">
					<Col span="24">
					<FormItem label="商户ID" prop="buId">
						<Input v-model="updateInfo.buId" placeholder="请输入商户ID"></Input>
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="商户快信通账号" prop="creditAccount">
						<Input v-model="updateInfo.creditAccount" placeholder="请输入商户快信通账号"></Input>
					</FormItem>
					</Col>
				</Row>
			</Form>
			<template #footer>
				<Button type="text" @click="onCancelUpdate">取消</Button>
				<Button type="primary" @click="onConfirmUpdate" :loading="loading">确定</Button>
			</template>
		</Modal>
	</div>
</template>
<script>
import { mapState } from 'vuex'
import { hasOneOf } from '@/libs/tools'
import { RolesType, RegExpConst } from '@/constants'
import { getUserList, addUser, resetPassword, updateUserInfo } from '@api/user'

export default {
	data() {
		return {
			loading: false,
			list: [],
			selectedData: [],
			pageNum: 1,
			pageSize: 10,
			total: 0,
			tableSize: 'small',
			tableFullscreen: false,
			addInfo: {
				username: '',
				phoneNo: '',
			},
			addRules: {
				username: [
					{ required: true, message: `请输入用户名` },
					{ ...RegExpConst.name }
				],
				phoneNo: [
					{ required: true, message: '请输入手机号' },
					{ ...RegExpConst.phoneNo }
				]
			},
			addVisible: false,
			currentUser: {},
			updateInfo: {
				buId: '',
				creditAccount: '',
			},
			updateRules: {
				buId: [
					{ required: true, message: `请输入商户ID` },
				],
				creditAccount: [
					// { required: true, message: `请输入商户快信通账号` },
				]
			},
			updateVisible: false,
		}
	},
	computed: {
		...mapState('admin/common', [
      'publicConfig'
    ]),
		...mapState('admin/user', [
			'info', 'allUsers'
		]),
		...mapState('admin/role', [
			'roles'
		]),
		hasT() {
			return hasOneOf(this.info.roleCodeList, RolesType.T)
		},
		hasT_M_L1() {
			return hasOneOf(this.info.roleCodeList, RolesType.T_M_L1)
		},
		isSpark() {
			const { adminDomain = '' } = this.publicConfig
			return adminDomain.indexOf('admin.sparknt') > -1 || process.env.NODE_ENV === 'development'
		},
		columns() {
			return [
				{ title: '姓名', key: 'name', slot: 'name', minWidth: 140, show: true },
				{
					title: '角色',
					key: 'roleCodeList',
					minWidth: 160,
					show: true,
					render: (h, { row }) => {
						const roleCodeName = {}
						this.roles.forEach(role => {
							roleCodeName[role.roleCode] = role.roleName
						})
						if (row.roleCodeList && row.roleCodeList.length) {
							if (row.roleCodeList.length === 1 && row.roleCodeList[0] === 'L2') {
								return h('span', {
									style: {
										color: '#f90'
									}
								}, '待定')
							}
							return h('span', `${row.roleCodeList.map(r => roleCodeName[r]).join('，')}`)
						} else {
							return h('span', {
								style: {
									color: '#f90'
								}
							}, '待定')
						}
					}
				},
				{ title: '所属部门', key: 'name', slot: 'name', minWidth: 140, show: true },
				{ title: '手机号', key: 'phoneNo', minWidth: 200, show: true },
				{ title: '状态', key: 'status', slot: 'status', minWidth: 100, show: true },
				{ title: '创建时间', key: 'createTime', minWidth: 200, show: true },
				{
					title: '操作',
					key: 'action',
					slot: 'action',
					align: 'center',
					width: 140,
					show: true,
					fixed: 'right'
				}
			]
		},
		// 动态设置列
		tableColumns() {
			const columns = [...this.columns];
			return columns.filter(item => item.show);
		},
		dropdownColumns() {
			return this.columns.filter(item => item.title)
		}
	},
	methods: {
		async getData() {
			if (this.loading) return;
			this.loading = true;
			// 下面的 params 是获取的表单查询参数
			const params = this.$parent.$parent.$refs.form.data;
			const response = await getUserList({
				name: params.name,
				phoneNo: params.phoneNo,
				pageSize: this.pageSize,
				pageNum: this.pageNum,
			})
			this.list = response.records || [];
			this.total = response.total;
			this.loading = false;
		},
		onChangeTableSize(size) {
			this.tableSize = size;
		},
		onFullscreen() {
			this.tableFullscreen = !this.tableFullscreen;
			this.$emit('on-fullscreen', this.tableFullscreen);
		},
		onRefresh() {
			this.getData();
		},
		onChangePage(page) {
			this.pageNum = page;
			this.getData();
		},
		onChangePageSize(size) {
			this.pageNum = 1;
			this.pageSize = size;
			this.getData();
		},
		onSearch() {
			this.pageNum = 1;
			this.getData();
		},
		onAdd() {
			this.addVisible = true
		},
		onCancelAdd() {
			this.$refs.addInfo.resetFields()
			this.addVisible = false
			this.addInfo = {
				username: '',
				phoneNo: '',
			}
		},
		onConfirmAdd() {
			this.$refs.addInfo.validate(async (valid) => {
				if (valid) {
					this.loading = true
					const response = await addUser({
						name: this.addInfo.username,
						phoneNo: this.addInfo.phoneNo,
					})
					this.loading = false
					if (response.code === 1000) {
						this.$Message.success('新增成功')
						this.onCancelAdd()
						this.getData()
					}
				}
			})
		},
		async onDeleteUser(user) {
			const response = await updateUserInfo({
				userId: user.userId,
				isDelete: 1
			})
			if (response.code === 1000) {
				this.$Message.success('删除成功')
				this.pageNum = 1
				this.getData()
			}
		},
		async onResetPassword(user) {
			const response = await resetPassword({
				userId: user.userId
			})
			if (response.code === 1000) {
				this.$Message.success('重置成功')
			}
		},
		onUpdateInfo(row) {
			this.updateVisible = true
			this.$refs.updateInfo.resetFields()
			this.updateInfo = {
				buId: row.buId,
				creditAccount: row.creditAccount
			}
			this.currentUser = row
		},
		onCancelUpdate() {
			this.$refs.updateInfo.resetFields()
			this.updateVisible = false
			this.updateInfo = {
				buId: '',
				creditAccount: ''
			}
		},
		onConfirmUpdate() {
			this.$refs.updateInfo.validate(async (valid) => {
				if (valid) {
					this.loading = true
					const response = await updateUserInfo({
						userId: this.currentUser.userId,
						buId: this.updateInfo.buId,
						creditAccount: this.updateInfo.creditAccount
					})
					this.loading = false
					if (response.code === 1000) {
						this.$Message.success('更新成功')
						this.onCancelUpdate()
						this.getData();
					}
				}
			})
		},
	}
}
</script>
<style lang="less">
.add-user-modal {
	.ivu-form-item-label {
		width: 100%;
		text-align: left;
	}
}
</style>
